// components/songTab/index.js
Component({
  options: {
    addGlobalClass: true,
    styleIsolation: 'isolateds'
  },
  pageLifetimes: {
    show: function () {
      const songState = wx.getStorageSync('musicPlaybackState')
      const lyricState = wx.getStorageSync('lyricState');
      const flag = wx.getStorageSync('istabRunning')
      const songList = wx.getStorageSync('songlist')
      if(lyricState&& songState){
        this.setData({
          targetSeconds: Number.parseInt(lyricState.targetSeconds), // 目标秒数，可以根据需要动态改变
          currentTime: lyricState.currentTime+Number.parseFloat(1), // 当前已过时间，初始为0
          progress: lyricState.progress, // 进度百分比，初始为0
          istabRunning: flag.istabRunning, // 是否正在运行，用于控制播放和暂停
          song: JSON.parse(songState.song),
          songlist:JSON.parse(songList)
          
        })
      }
        // 组件挂载时初始化音频上下文
        this.initAudio();
        // 尝试恢复播放状态
        this.restorePlaybackState();
      if (this.data.istabRunning) {
        this.onResume();
      }
    },
    hide: function () {
      if(this.data.istabRunning){
        this.onPause();
        wx.setStorageSync('istabRunning', {istabRunning:false})
        wx.setStorageSync('flag', {isRunning: true})
      }else{
        this.onPause();
        wx.setStorageSync('istabRunning', {istabRunning:false})
        wx.setStorageSync('flag', {isRunning: false})
      }
     
    },
    resize: function () {}
  },

  /**
   * 组件的属性列表
   */
  properties: {
  },


  /**
   * 组件的初始数据
   */
  data: {
    targetSeconds: 277, // 目标秒数，可以根据需要动态改变
    currentTime: 0, // 当前已过时间，初始为0
    progress: 0, // 进度百分比，初始为0
    seconds: 0, //已播放时间
    scrollTop: 0, //歌词
    // isRunning: false, // 是否正在运行，用于控制播放和暂停
    audioCtx: null,
    istabRunning: false,
    song: null,
    songlist: [],

  },
  lifetimes: {
    attached() {

    },
    detached() {
      // 组件卸载时清理音频上下文
      if (this.data.audioCtx) {
        this.data.audioCtx.stop();
        this.data.audioCtx.destroy();

      }
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {

    onClickInfo() {
      this.setData({
        show: true
      });
    },
    onClose() {
      this.setData({
        show: false
      });
    },
    onMediaInfo(newVal) {
      console.log(newVal);
    },
    restorePlaybackState() {
      const storedState = wx.getStorageSync('musicPlaybackState');
      const istabRunning = wx.getStorageSync('istabRunning')
      const lyricState = wx.getStorageSync('lyricState')
      if (storedState) {
        // 如果有存储的状态，则恢复
        this.setData({
          targetSeconds: lyricState.targetSeconds,
          istabRunning: istabRunning.istabRunning,
          currentTime: lyricState.currentTime,
          progress: lyricState.progress,
          seconds: lyricState.seconds, //当前播放的进度
          scrollTop: lyricState.scrollTop, //当前歌词下标
          song: JSON.parse(storedState.song) || this.data.song, // 确保默认值或当前数据不被覆盖

        });
        if (lyricState.seconds > 0) {
          this.data.audioCtx.seek(lyricState.seconds);
          // 确保 seek 后再根据状态播放
          setTimeout(() => {
            if (this.data.istabRunning) {
              this.onResume();
            }
          }, 100); // 稍作延迟，等待 seek 完成
        } else {
          if (this.data.istabRunning) {
            this.onResume();
          }
        }
      }
    },

    initAudio() {
      this.setData({
        audioCtx: wx.createInnerAudioContext(),
      });
      this.data.audioCtx.src = this.data.song.song_path;

      this.data.audioCtx.onTimeUpdate(() => {

        this.updateProgress();
      });
      this.data.audioCtx.onEnded(() => {
        this.onPause();
      });
    },

    togglePlay() {
     
      if (this.data.istabRunning) {
        this.onPause();
      } else {
        this.onResume();
      }
    },

    onResume() {
      this.setData({
        istabRunning: true,
      });
      this.data.audioCtx.play();
      this.updateProgress();
    },

    onPause() {
      this.setData({
        istabRunning: false,
      });
      this.data.audioCtx.pause();
      // 保存播放状态到本地存储
      wx.setStorageSync('musicPlaybackState', {
        song: JSON.stringify(this.data.song), // 注意，这里存储的是引用类型，实际应用中可能需要转换为字符串或其他可序列化的格式
      });
      wx.setStorageSync('istabRunning', {
        istabRunning: this.data.istabRunning,

      })
      wx.setStorageSync('lyricState', {
        targetSeconds: this.data.targetSeconds,
        currentTime: this.data.currentTime,
        progress: this.data.progress,
        seconds: this.data.seconds, //当前播放的进度
        scrollTop: this.data.scrollTop, //当前歌词下标
      })
    },

    updateProgress() {
      const {
        currentTime,
        targetSeconds
      } = this.data;
      const percent = Math.floor((currentTime / targetSeconds) * 100); // 计算进度百分比
      this.setData({
        progress: Math.min(percent, 100)
      }); // 更新进度，确保不超过100%

      if (currentTime < targetSeconds && this.data.istabRunning) {
        setTimeout(() => {
          this.setData({
            currentTime: this.data.audioCtx.currentTime,
            seconds: this.data.audioCtx.currentTime,
          });
          wx.setStorageSync('lyricState', {
            targetSeconds: this.data.targetSeconds,
            currentTime: this.data.currentTime,
            progress: this.data.progress,
            seconds: this.data.seconds, //当前播放的进度
            scrollTop: this.data.scrollTop, //当前歌词下标
          })
       
        }, 1000); // 每秒更新一次

        
        wx.setStorageSync('istabRunning', {
          istabRunning: this.data.istabRunning,
        })
      } else if (currentTime >= targetSeconds) {
        this.onPause(); // 结束时自动暂停
      }
    },
    onClickLyric() {
      wx.navigateTo({
        url: '../../pages/lyric/index',
      })
    },
    onClickSong(e){
      this.data.audioCtx.destroy();
      const {item} = e.currentTarget.dataset
     
     if(this.data.song.song_id!=item.song_id){
   
      wx.setStorageSync('musicPlaybackState', {song:JSON.stringify(item)});
      this.setData({
        song:item,
        targetSeconds: Number.parseFloat(item.song_duration),
      })
      wx.setStorageSync('lyricState', {
        targetSeconds: Number.parseFloat(item.song_duration),
        currentTime: 0,
        progress:0,
        seconds: 0, //当前播放的进度
        scrollTop: 0, //当前歌词下标
      })
      wx.setStorageSync('istabRunning', {
        istabRunning: true
      })
        // 组件挂载时初始化音频上下文
        this.initAudio();
        // 尝试恢复播放状态
        this.restorePlaybackState();
     }
    }
    
  },

})